﻿using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Lab3MiddleTier;
using Lab3MiddleTier.Model;

namespace NinjaLoot2.Controllers
{
	[Authorize(Roles="Member")]
    public class UploadController : Controller
	{

		private MiddleTier _middle = new MiddleTier(ConfigurationManager.ConnectionStrings["BackendMySQL"].ConnectionString);

        //
        // GET: /Upload/
        public ActionResult Index()
        {
            return View();
        }

		[HttpPost]
		public ActionResult UploadFile(UserFile userfile , HttpPostedFileBase file)
		{
			if(file.ContentLength> 0)
			{
				
				var user = Membership.GetUser();
				var fileName = Path.GetFileName(file.FileName);
				var duser = _middle.GetUserByUsername(user.UserName);
				var dfile = new UserFile();

				BinaryReader br = new BinaryReader(file.InputStream);
				byte[] blob = br.ReadBytes((int)file.InputStream.Length);

				dfile.Owner = duser;
				dfile.Name = fileName;
				dfile.Size = file.ContentLength;
				dfile.Type = file.ContentType;
				dfile.FileBytes = blob;

				_middle.AddFile(dfile);
			}

			return RedirectToAction("Index");
		}

    }
}
